<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            width: 300px;
            height: 300px;
            border: 1px solid silver;
        }
    </style>
</head>
<body>
    <button>点击发送请求。。。</button>
    <button>取消请求</button>
    <div id="box"></div>
    <script>

        const btn1 = document.getElementsByTagName("button")[0];
        const btn2 = document.getElementsByTagName("button")[1];
        const box = document.getElementById("box");
        let xhr;
        let isSending = false;
        btn1.onclick = function (){
            if(isSending) xhr.abort();
            xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open("get","http://localhost:8000/server?a=100&b=300");
            xhr.send();
            //readystate 0:未初始化 1：open方法调用完毕 2：send方法调用完毕 3：服务端返回部分结果 4：服务端返回所有结果
            xhr.onreadystatechange = function (){
                if(xhr.readyState === 4){
                    isSending = false;
                    if(xhr.status >= 200 && xhr.status < 300){
                        // console.log(xhr.status)
                        // console.log(xhr.statusText)
                        // console.log(xhr.getAllResponseHeaders())
                        // console.log(xhr.response)
                        box.innerHTML = xhr.response;
                    }
                }
            };
            xhr.timeout=4000;
            xhr.ontimeout = function (){
                console.log("超时了");
            };
            xhr.onerror = function(){
                console.log("网络出错了")
            };
        };

        btn2.addEventListener("click",function (){
            xhr.abort();
        })
    </script>
</body>
</html>